<?php
    @include_once("conn.php");

    $key = $_GET["key"];  // 搜索的关键词
    $pageIndex = $_GET["pageIndex"];  // 页码(第几页)
    $showNum = $_GET["showNum"];  // 每页显示多少条 (5,10,15,20)
	

    if(!($pageIndex&&$showNum)){
        argErr();
    }   

    // 页码 pageIndex  每页显示数据:showNum
    // 第1页  limit 0,5  
    // 第2页  limit 5,5  
    // 第3页  limit 10,5  

    // pageIndex    limit  (pageIndex-1)*showNum,showNum

    // 问题$pageIndex没有最小值和最大值限制 可能超出范围 => 查询出错
    // 解决方法 对最小值和最大值进行限制
    // 最小值 = 1
    // 最大值 = allCount(总数据) / showNum => 向上取整

    // 如何查找满足条件的总数据  select count(*) as allCount from `grade` where name like '%$key%'

    $search = "select count(*) as allCount from `goodslist` where goodsName like '%$key%'";
    $result = mysqli_query($conn,$search);
    $item = mysqli_fetch_assoc($result);
    // print_r($item);
    $allCount = $item["allCount"];

    $maxPage =  ceil($allCount/$showNum);
    // echo $maxPage;

    if($pageIndex>$maxPage){
        $pageIndex = $maxPage;
    }

    if($pageIndex<1){
        $pageIndex = 1;
    }
    

    $skipNum = ($pageIndex-1)*$showNum; 

    $sql = "select id,goodsId,goodsName,goodsPrice,bigPicList from `goodslist` where goodsName like '%$key%' order by id asc limit $skipNum,$showNum";
    // echo $sql;

    $result = mysqli_query($conn,$sql);

    $all = array();
    while($item = mysqli_fetch_assoc($result)){

        // 数据预处理
        // $item["smallPicList"] = explode(",",$item["smallPicList"]);
        $item["bigPicList"] = explode(",",$item["bigPicList"]);
        $item["goodsImg"] =  $item["bigPicList"][0];

        array_push($all,$item);
    }

    $obj = array();
    if(count($all)>0){
        $obj["status"] = true;
        $obj["detail"] = "ok";
        $obj["maxPage"] = $maxPage;   //最大页
        $obj["allCount"] = $allCount*1; //总数据(满足条件)
        $obj["list"] = $all;
    }else{
        $obj["status"] = false;
        $obj["detail"] = "暂无数据";
    }

    echo json_encode($obj);

?>